 //载入方案
 var fix_rule=50;//内部长度单位到像素
 var fix_danwei=2.5;//内部长度单位到实际单位mm
 var editor_json={};
 function load(json,dragMode="") {
 	 $('svg').children(".hhl").empty();
	 cur_data=json;
	 let vertexs=json.vertexs;
	 let cutting_stack=[];
	 let d="";
	 for(let i=0;i<vertexs.length;i++)
	 {
		 
		 let d1="";
		 let action="";
		 let nextnode,prenode;
		 let r1=5;
		 let cur_node=vertexs[i];
		 if(cur_node.r&&cur_node.r>r1)  r1=cur_node.r;
		 
		 if(i==0)
		 {
			 d+="M"+cur_node.x+" "+cur_node.y;
			 prenode=vertexs[vertexs.length-1];
			 nextnode=vertexs[i+1];
		 }
		 else if(i==vertexs.length-1)
		 { 
	         prenode=vertexs[i-1];
			 nextnode=vertexs[0];
		 }
		 else
		 {
			 nextnode=vertexs[i+1];
			 prenode=vertexs[i-1];
		 }
		 cur_node.nextnode=nextnode;
		 cur_node.prenode=prenode;
		 
		 
		 let valueText =  Math.round((qSVG.measure(cur_node,nextnode))*fix_danwei);//.toFixed(2); 
	 	 let dom = qSVG.create("box_editline", "line", { 
	 		   index:i,
			   l:valueText,
			   class: "line_hhl",
			    objectType:"line_hhl",
						x1:cur_node.x, y1:cur_node.y,
						x2:nextnode.x, y2:nextnode.y,
						'opacity':0,
						'stroke':'#5cba79',
						'stroke-width':"8",
						 r: r1
			});
			
	    //let angle = qSVG.angle(prenode,cur_node,nextnode);
		 
		let angle = qSVG.angle(prenode.x,prenode.y,cur_node.x,cur_node.y,nextnode.x,nextnode.y);
		//angle = qSVG.vectorAngle(prenode,cur_node);
	    cur_node.a=angle.deg;
        {
			let isout=1;
			let polygon=[];
			   for(let j=0;j<vertexs.length;j++)
			   {
				   if(j!=i)
				   {
					   polygon.push(vertexs[j]);
				   }
				   
			   }
			   if (qSVG.rayCasting(cur_node, polygon)) {
                   isout=0;
				   cur_node.a=360-cur_node.a;
               }
			   
		}
		
           dom = qSVG.create("box_editcircle", "circle", { 
		   index:i,
		   objectType:"circle_hhl",
		   class: "circle_hhl",
                    cx:cur_node.x, cy:cur_node.y,
					'fill-opacity':0,
					'fill':'#5cba79',
                     r: r1
		});
		
		 let startText = qSVG.middle(nextnode.x, nextnode.y,cur_node.x, cur_node.y);
         let angleText = qSVG.angle(cur_node.x, cur_node.y, nextnode.x, nextnode.y);
		
		 
                      lengthTemp = document.createElementNS('http://www.w3.org/2000/svg', 'text');
                      lengthTemp.setAttributeNS(null, 'x', startText.x-15);
                      lengthTemp.setAttributeNS(null, 'y', (startText.y-15) );
                      lengthTemp.setAttributeNS(null, 'text-anchor', 'middle');
                      lengthTemp.setAttributeNS(null, 'stroke', 'none');
                      lengthTemp.setAttributeNS(null, 'stroke-width', '0.6px');
                      lengthTemp.setAttributeNS(null, 'fill', '#777777');
                      lengthTemp.textContent = valueText;
					  lengthTemp.setAttribute("transform", "rotate(" + angleText.deg + " " + startText.x + "," + startText.y + ")");

                      $('#boxpath').append(lengthTemp);
					  
     let enter_stack=false;
	 if(cur_node.cuttingIndex!=null) 
	 {
		 if(cutting_stack.length>0)
		 {
			 
			 if(Math.floor(cutting_stack[cutting_stack.length-1].cuttingIndex/2)==Math.floor(cur_node.cuttingIndex/2))
			 {
				let node=cutting_stack.pop();
				console.log(node);
				 let dom = qSVG.create("box_editline", "line", { 
	 		 
			   class: "cuttingline_hhl",
			    cuttingIndex:cur_node.cuttingIndex,
			    objectType:"cuttingline_hhl",
						x1:cur_node.x, y1:cur_node.y,
						x2:node.x, y2:node.y,
						'opacity':1,
						'stroke':'#ff0000',
						'stroke-width':"1",
					 
		     	});
			 }
			 else
			 {
				 enter_stack=true;
			 }
		 }
		 else
		 {
			 enter_stack=true;
		 }
		 if(cur_data.cuttingpointCount%2==0)
		 {
			 if(cur_data.cuttingpointCount==cur_node.cuttingIndex)
			 {
				  enter_stack=false;
			 }
		 }
		 
	 }
	 if(enter_stack)
	 {
		 cutting_stack.push(cur_node);
	 }
	   
	  
	  
	    //let angle3=qSVG.angle(prenode.x, prenode.y,vertexs[i].x, vertexs[i].y, nextnode.x, nextnode.y);	
		// if(angle3.deg==90||angle3.deg==0)
		 if(vertexs[i].r&&(vertexs[i].r!=0))
		 {
			 
			 let isout=1;
			
			 let x0=x1=vertexs[i].x;
			 let y0=y1=vertexs[i].y;
		 
			   
			 
			 if(prenode.x==vertexs[i].x)
			 {
				 if(prenode.y>cur_node.y)
				 {
					 y0=cur_node.y+cur_node.r;
				 }
				 else
				 {
					 y0=cur_node.y-cur_node.r;
				 }
			 }
			 if(prenode.y==cur_node.y)
			 {
				 if(prenode.x>cur_node.x)
				 {
					 x0=cur_node.x+cur_node.r;
				 }
				 else
				 {
					 x0=cur_node.x-cur_node.r;
				 }
			 }
			 if(nextnode.y==cur_node.y)
			 {
				 if(nextnode.x>cur_node.x)
				 {
					 x1=cur_node.x+cur_node.r;
				 }
				 else
				 {
					 x1=cur_node.x-cur_node.r;
				 }
			 }
			 if(nextnode.x==cur_node.x)
			 {
				 if(nextnode.y>cur_node.y)
				 {
					 y1=cur_node.y+cur_node.r;
				 }
				 else
				 {
					y1=cur_node.y-cur_node.r;
				 }
			 }
			if(i==0)
		    {
			 d+="M "+x0+" "+y0;
			}
			else
			{
				 d+=" L "+x0+" "+y0;
			}
			
			   let polygon=[];
			   for(let j=0;j<vertexs.length;j++)
			   {
				   if(j!=i)
				   {
					   polygon.push(vertexs[j]);
				   }
				   else
				   {
					     polygon.push({x:x0,y:y0});
						 polygon.push({x:x1,y:y1});
				   }
			   }
			   if (qSVG.rayCasting(cur_node, polygon)) {
                   isout=0;
                }
			  d+=" A "+cur_node.r+" "+cur_node.r+" 0 0 "+isout+" "+x1+" "+y1+" ";
			 
			 continue;
			 
		 }
		 else
		 {
			  action="L";
		 }
         d+=action+cur_node.x+" "+cur_node.y+d1+" ";
	 }
	  d+=" Z";
 
 
     dom = qSVG.create("boxBase", "path", { 
	 
      d,
      "stroke": "#666",
      "stroke-width":3,
      fill : "#ffffff"
    });
	
	 
	 
	$(".circle_hhl").mouseout(function(){
		$(this).attr("fill-opacity",0);
	});
	$(".circle_hhl").mouseover( function(){
		$(this).attr("fill-opacity",1);
	});
	$(".circle_hhl").dblclick( function(){
		return;
		 //alert($(this).attr("index"));
		 editor_json={index:$(this).attr("index")*1};
		 
		 $('#myModal_editVertex [name=r]').val(cur_data["vertexs"][editor_json.index].r);
		  $('#myModal_editVertex [name=a]').val(cur_data["vertexs"][editor_json.index].a);
		 $('#myModal_editVertex').modal();
		 drag = 'off';
	});
	$(".circle_hhl").mousedown(function(){
		 
		//moveingObject=$(this); 
		
		let index= $(this).attr("index")*1;
		if($("#movingDom")[0])
		 {
 			 let objectType=$("#movingDom").attr("objectType");
				if(objectType=="circle_deleteNode")
				{
				  
				   cur_data["vertexs"].splice(index,1);
				   load(cur_data);
				   
				}
				else if(objectType=="circle_addCuttingNode")
				{
 				   if(cur_data.cuttingpointCount==null)
					{
						cur_data.cuttingpointCount=0;
					}
					else
					{
						
						cur_data.cuttingpointCount++;
					}
				 
				   cur_data["vertexs"][index].cuttingIndex=cur_data.cuttingpointCount;
				   load(cur_data);
				 
				}
		 }
	});
	
	$(".cuttingline_hhl").mousedown(function(){
		
		let cuttingIndex= $(this).attr("cuttingIndex")*1;
		 
		if($("#movingDom")[0])
		 {
 			    let objectType=$("#movingDom").attr("objectType");
				if(objectType=="circle_deleteCuttingNode")
				{
				   $("#movingDom").attr("fill-opacity",0);
			        $("#movingDom").attr("opacity",0);
				   for(let j=0;j<cur_data["vertexs"].length;j++)
				   {
					   if(cur_data["vertexs"][j].cuttingIndex!=null)
					   if(Math.floor(cur_data["vertexs"][j].cuttingIndex/2)==Math.floor(cuttingIndex/2))
					   {
						   cur_data["vertexs"][j].cuttingIndex=null;
					   }
				   }
				   load(cur_data);
				  
				   
				}
				 
		 }
		
	});
	$(".cuttingline_hhl").mouseover( function(){
		
		 if($("#movingDom")[0])
		{
		        let objectType=$("#movingDom").attr("objectType");
				if((objectType=="circle_deleteCuttingNode"))
				{
					$("#movingDom").attr("fill-opacity",1);
			        $("#movingDom").attr("opacity",1);
				}
			 
			  
		}
	});
 
	$(".cuttingline_hhl").mouseout(function(){
		if($("#movingDom")[0])
		{
		        let objectType=$("#movingDom").attr("objectType");
				if((objectType=="circle_deleteCuttingNode"))
				{
					$("#movingDom").attr("fill-opacity",0);
			        $("#movingDom").attr("opacity",0);
				}
			 
			  
		}
		 
		
	});
	$(".line_hhl").mousedown(function(){
		moveingObject=$(this); 
		 drag="on";
	    $(this).attr("opacity",1);
		 
		
	});
	$(".line_hhl").mouseout(function(){
		if($("#movingDom")[0])
		{
		       let objectType=$("#movingDom").attr("objectType");
				if((objectType=="circle_deleteNode")||(objectType=="circle_addNode")||(objectType=="circle_addCuttingNode"))
				{
					$("#movingDom").attr("fill-opacity",0);
			        $("#movingDom").attr("opacity",0);
				}
			 
			  editor_json.cx=null;
			  editor_json.cy=null;
 			 //drag="off";
		}
		else
		{
			$(this).attr("opacity",0);
		}
		
	});
	$(".line_hhl").mouseover( function(){
		
		if($("#movingDom")[0])
		{
			    let objectType=$("#movingDom").attr("objectType");
				if((objectType=="circle_deleteNode")||(objectType=="circle_addNode")||(objectType=="circle_addCuttingNode"))
				{
				  moveingObject= $("#movingDom");
				  moveingObject.attr("fill-opacity",1);
				  moveingObject.attr("opacity",1);
				  editor_json.cx=moveingObject.attr('cx');
				  editor_json.cy=moveingObject.attr('cy');
				  editor_json.index=$(this).attr("index")*1;
				}
				
		     
			// moveingObject=$("#movingDom");
			// drag="on";
		}
		else
		{
			$(this).attr("opacity",1);
		}
	});
 
	$(".line_hhl").dblclick( function(){
		
		 editor_json={index:$(this).attr("index")*1,old_l:$(this).attr("l")*1};
		 $('#myModal_editLine [name=l]').val($(this).attr("l")*1);
		 $('#myModal_editLine').modal();
		 drag = 'off';
	});
 
 }
 //提供初始化方案
 var initPlan=
 {
	"plan_1": function()
	 {
		 let json={};
		 json.vertexs=[];
		 json.vertexs.push({x:0,y:0,r:0});
		 json.vertexs.push({x:450,y:0,r:0});
		 json.vertexs.push({x:450,y:500,r:0});
		 json.vertexs.push({x:200,y:500,r:0});
		 json.vertexs.push({x:0,y:500,r:0});
		 return json;
	 },
	 "plan_2": function()
	 {
		  let json={};
		 json.vertexs=[];
		 json.vertexs.push({x:0,y:0,r:0});
		 json.vertexs.push({x:500,y:0,r:0});
		 json.vertexs.push({x:500,y:500,r:0});
		 json.vertexs.push({x:300,y:500,r:0});
		 json.vertexs.push({x:300,y:200,r:0});
		 json.vertexs.push({x:0,y:200,r:0});
		 return json;
	 },
	 
 };
 $(document).ready(function(){
	 $(document).bind("contextmenu",function(e){
        return false;
    });
	 load(initPlan["plan_1"]());
	  zoom_maker('zoomdrag', width_viewbox/4, height_viewbox/4);
	  zoom_maker('zoomin', 400);
	 
	 var zoomBtn = document.querySelectorAll('.zoom');
	  for (var k = 0; k < zoomBtn.length; k++) {
		zoomBtn[k].addEventListener("click", function () {
			lens = this.getAttribute('data-zoom');
			zoom_maker(lens, 200);
		})
	}
	
	
	    document.querySelector('#lin').addEventListener("mouseup", _MOUSEUP);
		//document.querySelector('#lin').addEventListener("mousemove", throttle(function(event){ _MOUSEMOVE(event);},0));
		document.querySelector('#lin').addEventListener("mousemove",_MOUSEMOVE); 
		document.querySelector('#lin').addEventListener("mousedown", _MOUSEDOWN, true);
		
		$("#selectModel").click(function(){
			$('#myModal').modal();
		});
		$("#export_plan").click(function(){
			export_plan();
		});
		$(".modelbtn").click(function(){
			
			$("#movingDom").remove(); 
			let dom=$(this);
			let model=dom.attr("model");
	 
			if(dom.hasClass('btn-success'))
			{
				 
				dom.removeClass('btn-success');
			}
			else
			{
		      $('.btn-success').removeClass('btn-success');
			  dom.addClass('btn-success');
			  addObject(model);
				
			}
             
		});
      
 });
  

 function save_editVertex()
{
	
	 let index=editor_json.index;
	 let cur_node=cur_data["vertexs"][index];
	 let prenode=cur_node.prenode;
	 let nextnode=cur_node.nextnode;
	 let r=$('#myModal_editVertex [name=r]').val()*1;
	 if(!r) r=0;
     index.r=r;
	 
	 let new_a=$('#myModal_editVertex [name=a]').val()*1;
	 if(new_a!=90) index.r=0;
 	  //1.定点，角度旋转，求新直线方程
	 let new_equation={k:0,b:0};
	 //let a1=qSVG.vectorAngle(cur_node.prenode,cur_node);
	 let temp=Math.round(Math.atan((cur_node.y-prenode.y),(cur_node.x-prenode.x))* (180/Math.PI));
	 let A, B;
	 
	 let k_a=180-(temp+new_a);
	 if((k_a==90)||(k_a==-90)) {A="h",B=cur_node.y;}
	 else if((k_a==0)||(k_a==180)||(k_a==-180)) {A="h",B=cur_node.y;}
	 else{
		  A=Math.tan(k_a/(180/Math.PI));
	      B=cur_node.y-A*cur_node.x;
	 }
	 console.log({A,B});
	 console.log(qSVG.createEquation(nextnode,nextnode.nextnode));
	 let newpoint=qSVG.intersectionOfEquations({A,B},qSVG.createEquation(nextnode,nextnode.nextnode),"object");
	 nextnode.x=newpoint.x;
	 nextnode.y=newpoint.y;
	 
	 load(cur_data);
	 $('#myModal_editVertex').modal('toggle');
}
 function save_editLine()
{
	
	 let index=editor_json.index;
	 let old_l=editor_json.old_l;
	 let l=$('#myModal_editLine [name=l]').val();
	 if(!l) return;
	 l=l*1;
     let svg_length=(old_l-l)/fix_danwei;
	 
	  console.log(l);
	  console.log(old_l);
 	  let cur_node=cur_data["vertexs"][index];
	  let nextnode=cur_node.nextnode;
	  let prenode=cur_node.prenode;
	 
      if(cur_node.y==nextnode.y)
	  {
		  let bigger=Math.abs(cur_node.x)>Math.abs(nextnode.x)?cur_node:nextnode;
		   findNearNext(bigger,svg_length,"x");
		  bigger.x-=svg_length;
	  }
	  else
	  {
		  let bigger=cur_node.y>nextnode.y?cur_node:nextnode;
		  findNearNext(bigger,svg_length,"y");
		  bigger.y-=svg_length;
	  }	
	 
	 load(cur_data);
	 $('#myModal_editLine').modal('toggle');
	 
	 function findNearNext(cur_node,add_l,direction)
	 {
		 let nextnode=cur_node.nextnode;
	     let prenode=cur_node.prenode;
		  for(let i=0;i<cur_data["vertexs"].length/2+1;i++)
		  {
			  if(cur_node[direction]==nextnode[direction])
			  {
				  nextnode[direction]-=add_l;
				  return;
			  }
			  if(cur_node[direction]==prenode[direction])
			  {
				  prenode[direction]-=add_l;
				  return;
			  }
			  nextnode=cur_node.nextnode;
			  prenode=cur_node.prenode;
		  }
	 }
	 
}

var moveingObject=null;
function addObject(type)
{  
	
	let dom;
 
	if((type=="circle_addNode")||(type=="circle_deleteNode")||(type=="circle_addCuttingNode")||(type=="circle_deleteCuttingNode"))
	{
		 dom =$(qSVG.create("movingzone", "ellipse", { 
		            id:"movingDom",
		            objectType:type,
                    cx:0, cy:0,
					  "stroke": "#666",
                     "stroke-width":1,
					 "fill":"#f2eee5",
					 "fill-opacity":0,
					 "opacity":0,
                     rx: 4,ry: 4
		})) ;
 		
	}
	 
	else
	{
		$('#hole_list').toggle(200);
	}
	if(type=="ellipse")
	{
		 dom =$(qSVG.create("boxBase2", "ellipse", { 
		            objectType:type,
                    cx:0, cy:0,
					  "stroke": "#666",
                     "stroke-width":3,
					 "fill":"#f2eee5",
                     rx: 10,ry: 10
		})) ;
 		
	}
	else if(type=="rectangle")
	{
		 dom =$(qSVG.create("boxBase2", "rect", { 
		            objectType:type,
                    x:0, y:0,width:10,height:10,
					  "stroke": "#666",
                     "stroke-width":3,
					 "fill":"#f2eee5",
 		})) ;
 		
	}
	moveingObject=dom;
	dom.mousedown(function(){
		moveingObject=$(this); 
	});
	_MOUSEDOWN({pageX:0,pageY:0});
}
 
 
 